#include "kaleidoscope.h"
#include <QPainter>
#include <cmath>

Kaleidoscope::Kaleidoscope()
{
    pix.load(":/images/example.jpg");
    r=350;
    nAxis=2;
    angle=0;
    pol=getTriangle();
    brush.setTexture(pix.copy(100,100,250,250));
}
void Kaleidoscope::paintEvent(QPaintEvent *){
    QPainter paint(this);
    QImage img = pix.toImage();

    paint.setBrush(brush);
    paint.setPen(Qt::NoPen);
    paint.setRenderHint(QPainter::Antialiasing);
    paint.translate(this->width()/2,this->height()/2);
    paint.rotate(angle);
    draw(paint);

}

void Kaleidoscope::draw(QPainter &paint){
    for(int i=0;i<nAxis;++i){
        paint.drawPolygon(pol);
        paint.rotate(180.0/nAxis);
        QMatrix mat=paint.combinedMatrix();
        paint.setWorldMatrix(QMatrix(mat.m11(),mat.m12(),-mat.m21(),-mat.m22(),mat.dx(),mat.dy()));
        paint.drawPolygon(pol);
        paint.setWorldMatrix(mat);
        paint.rotate(180.0/nAxis);
    }
}
void Kaleidoscope::timerEvent(QTimerEvent* ){
    static double alfa=0;
    brush.setTexture(pix.copy(pix.width()/2+pix.width()/4*cos(alfa),pix.height()/2+pix.height()/4*sin(alfa),150,150));
    update();
    alfa+=M_PI/50;
}
QPolygon Kaleidoscope::getTriangle(){
    QPolygon wielokat(3);
    double angle=M_PI-M_PI/nAxis;
    wielokat[0]=QPoint(0,0);
    wielokat[1]=QPoint(int(r*cos(angle)-r),int(r*sin(angle)));
    wielokat[2]=QPoint(int(r*cos(-angle)-r),int(r*sin(-angle)));
    return wielokat;
}

void Kaleidoscope::setTexture(const QString& file){
    pix.load(file);
}

void Kaleidoscope::setAxis(int axis){
    nAxis=axis;
    pol=getTriangle();
}

int Kaleidoscope::getAxis(){
    return nAxis;
}

int Kaleidoscope::getAngle(){
    return angle;
}

void Kaleidoscope::setAngle(int ang){
    angle=ang;
}
int Kaleidoscope::getRadius(){
    return r;
}

void Kaleidoscope::setRadius(int radius){
    r=radius;
    pol=getTriangle();
}
void Kaleidoscope::setAnimation(bool enable){
    if(enable)
        animationTimer=startTimer(50);
    else
        killTimer(animationTimer);
}
